<template>
  <div class="announcement-container">
    <div class="header">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="公告标题">
          <el-input v-model="searchForm.title" placeholder="请输入公告标题" clearable />
        </el-form-item>
        <el-form-item label="创建人">
          <el-select v-model="searchForm.createBy" placeholder="请选择创建人" clearable style="width: 100px">
            <el-option v-for="item in userList" :key="item.id" :label="item.userName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button type="primary" @click="handleAdd">新增公告</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="loading" :data="tableData" border style="width: 100%">
      <el-table-column prop="title" label="公告标题" min-width="150" />
      <el-table-column prop="content" label="公告内容" min-width="200" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" min-width="180" />
      <el-table-column prop="createName" label="创建人" min-width="120" />
      <el-table-column fixed="right" label="操作" width="150">
        <template #default="{ row }">
          <el-button type="primary" v-show="checkUserAuth(2)" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" v-show="checkUserAuth(2)" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增公告' : '编辑公告'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入公告内容"
          />
        </el-form-item>
        <el-form-item label="附件" prop="attachment">
          <el-upload
              v-model:file-list="formFiles.fileList"
              :limit="3"
              :auto-upload="false"
              :on-exceed="handleExceed"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :file-list="formFiles.fileList"
              list-type="text"
          >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传1个文件，文件大小不超过10MB</div>
          </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="已传文件"  v-if="dialogType == 'edit' && fileListName.length > 0">
          <div class="uploaded-files">
            <el-tag
                v-for="(item, index) in fileListName"
                :key="index"
                class="file-tag"
                closable
                @close="handleRemoveFile(index)"
            >
              {{ item }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessage, ElMessageBox} from 'element-plus'
import type {Announcement, AnnouncementParams} from '@/types/announcement'
import {addAnnouncement, deleteAnnouncement, getAnnouncementList} from '@/api/announcement'
import {getUserListByType} from "@/api/user.ts";
import {types} from "sass";
import {checkUserAuth} from "@/utils/userAuth.ts";

const loading = ref(false)
const tableData = ref<Announcement[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const fileListName = ref([])

const searchForm = reactive<AnnouncementParams>({
  title: '',
  current: 1,
  size: 10,
  createBy: undefined,

})
const dateRange = ref<string[]>([])


const form = reactive({
  id: 0,
  title: '',
  content: '',
  fileName:''
})
const formFiles = reactive({
  fileList: [],
  uploadedFile: []
})

const userList = ref([])
const getUserListByTypeFun = () =>{
  const userQuery = {
    size: 1000,
    userType: 2
  }
  getUserListByType(userQuery).then(res=>{
    console.log(res)
    userList.value=res.records
  })

}

const rules: FormRules = {
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }]
}

// 获取公告列表
const getList = async () => {
  try {
    loading.value = true
    const res = await getAnnouncementList({
      ...searchForm,
      current: currentPage.value,
      size: pageSize.value,
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    })
    tableData.value = res.records
    total.value = res.total
  } catch (error) {
    console.error('获取公告列表失败:', error)
    ElMessage.error('获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 新增公告
const handleAdd = () => {
  dialogType.value = 'add'
  form.id = 0
  form.title = ''
  form.content = ''
  formFiles.fileList = []
  formFiles.uploadedFile = []
  dialogVisible.value = true
}

// 编辑公告
const handleEdit = (row: Announcement) => {
  dialogType.value = 'edit'
  form.id = row.id
  form.title = row.title
  form.content = row.content
  formFiles.fileList = []
  formFiles.uploadedFile = []
  if (row.fileName){
    form.fileName = row.fileName.split(';')
    fileListName.value = row.fileName.split(';')
  }
  dialogVisible.value = true
}
const handleRemoveFile = (index: number) => {
  fileListName.value.splice(index, 1)
}
// 删除公告
const handleDelete = (row: Announcement) => {
  ElMessageBox.confirm('确认删除该公告吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteAnnouncement(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除公告失败:', error)
      ElMessage.error('删除公告失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 先上传文件
        formFiles.uploadedFile = []
        if (formFiles.fileList.length > 0) {
          formFiles.fileList.forEach(item => {
            formFiles.uploadedFile.push(item.raw)
          })

        }
        if (dialogType.value === 'edit') {
          form.fileName = fileListName.value.join(';')
        }
        console.log(form.fileName)
        const submitData = {
          'announcementDTO': JSON.stringify(form),
          'attachments':formFiles.uploadedFile
        }
        await addAnnouncement(submitData)
        ElMessage.success('更新成功')
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 文件上传相关方法
const handleExceed = () => {
  ElMessage.warning('只能上传1个文件')
}

const handleRemove = (file: any) => {
  const index = formFiles.fileList.indexOf(file)
  if (index !== -1) {
    formFiles.fileList.splice(index, 1)
    formFiles.uploadedFile = []
  }
}

const beforeUpload = (file: File) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 分页相关
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getList()
}

onMounted(() => {
  getList()
  getUserListByTypeFun()
})
</script>

<style scoped>
.announcement-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.uploaded-files {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.file-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}
</style>
